package com.eastseeway.radioproject.engineer;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.eastseeway.radioproject.base.BaseViewModel;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromBottomBoard;
import com.eastseeway.radioproject.entities.BeanFromEnergyBoard;
import com.eastseeway.radioproject.entities.BeanFromNegativePressureBoard;
import com.eastseeway.radioproject.entities.BeanFromSwitchBoard;
import com.eastseeway.radioproject.entities.BottomBoardFunctionCode;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;

import java.nio.ByteBuffer;
import java.util.List;

import struct.StructException;

public class EngineerViewModel extends BaseViewModel<EngineerRepository> {
    private final MutableLiveData<String> toastInfo = new MutableLiveData<>();
//    private final MutableLiveData<String> machineType = new MutableLiveData<>("");
    private final MutableLiveData<String> handlePressure = new MutableLiveData<>("35");//手柄端请求的压力
    private final MutableLiveData<String> vBusVoltage = new MutableLiveData<>();//底板的电压
    private final MutableLiveData<Boolean> hasPressure = new MutableLiveData<>(true);//是否有负压
    //    public final MutableLiveData<String> pressureValue = new MutableLiveData<>();
    private final MutableLiveData<Boolean> isContinuousDischargeMode = new MutableLiveData<>(true);//是否连续模式
    public final MutableLiveData<String> continuousDischargeTime = new MutableLiveData<>("100");//连续模式下 连续放电时间
    public final MutableLiveData<String> idp = new MutableLiveData<>("10");
    public final MutableLiveData<String> idlp = new MutableLiveData<>("10");
    public final MutableLiveData<String> idhp = new MutableLiveData<>("10");

    public final MutableLiveData<String> freq = new MutableLiveData<>("1");
    public final MutableLiveData<String> power = new MutableLiveData<>("20");
    public final MutableLiveData<String> depth = new MutableLiveData<>("20");
    public final MutableLiveData<String> shengyucishu = new MutableLiveData<>("50");
    public final MutableLiveData<Boolean> isAutoNeedle = new MutableLiveData<>(true);
    public final MutableLiveData<String> interval = new MutableLiveData<>("500");
    public final MutableLiveData<Boolean> is2MHz = new MutableLiveData<>(false);
    public final MutableLiveData<Boolean> isNegativePressureHandle = new MutableLiveData<>(false);

    public EngineerViewModel(@NonNull Application application) {
        super(application);
    }

    @Override
    protected EngineerRepository setRepository() {
        return new EngineerRepository();
    }


    public void startSampleUpload() {
        commandStartSampleUpload(true);
    }

    public void closeResistance(){
        commandStartSampleUpload(false);
    }

    private void commandStartSampleUpload(boolean isStartSampleUpload) {
        try {
            int address;
            address = getHasPressure().getValue() ? Const.ADDRESS_TO_HANDLE_1_DATA_1 : Const.ADDRESS_TO_HANDLE_2_DATA_1;
            sendMessage(CommandGenerator.commandStartSampleUpload(address, isStartSampleUpload));
        } catch (StructException e) {
            e.printStackTrace();
        }
    }

    public void startOrStop(boolean isChecked) {
        try {
            byte[] commandDataToHandle;
            if (getHasPressure().getValue()) {
                commandDataToHandle = CommandGenerator.commandData1ToHandle1(Const.ADDRESS_TO_HANDLE_1_DATA_1,
                        Byte.parseByte(freq.getValue()),
                        Byte.parseByte(power.getValue()),
                        Byte.parseByte(depth.getValue()),
                        Byte.parseByte(handlePressure.getValue()),
                        Short.parseShort(continuousDischargeTime.getValue()),
                        Byte.parseByte(idp.getValue()),
                        Byte.parseByte(idhp.getValue()),
                        Byte.parseByte(idlp.getValue()),
                        isChecked,
                        !isContinuousDischargeMode.getValue(),
                        Byte.parseByte(shengyucishu.getValue()));
            } else {
                commandDataToHandle = CommandGenerator.commandData1ToHandle2(Const.ADDRESS_TO_HANDLE_2_DATA_1,
                        Byte.parseByte(freq.getValue()),
                        Byte.parseByte(power.getValue()),
                        Byte.parseByte(depth.getValue()),
                        isAutoNeedle.getValue(),
                        Short.parseShort(interval.getValue()),
                        Short.parseShort(continuousDischargeTime.getValue()),
                        Byte.parseByte(idp.getValue()),
                        Byte.parseByte(idhp.getValue()),
                        Byte.parseByte(idlp.getValue()),
                        isChecked,
                        !isContinuousDischargeMode.getValue(),
                        Byte.parseByte(shengyucishu.getValue()));
            }

            byte[] commandToEnergyBoard = CommandGenerator.commandToEnergyBoard(Const.ADDRESS_TO_ENERGY_BOARD, Byte.parseByte(freq.getValue()), !getIsContinuousDischargeMode().getValue(), !isChecked, Byte.parseByte(idp.getValue()));

            ByteBuffer buffer = ByteBuffer.allocate(commandDataToHandle.length + commandToEnergyBoard.length);
            buffer.put(commandToEnergyBoard);
            buffer.put(commandDataToHandle);
            sendMessage(buffer.array());
        } catch (StructException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException | NumberFormatException e) {
            toastInfo.setValue("请输入有效参数");
        }
    }

    //    负压板
    public void setHandlePressure() {
        String pressure = handlePressure.getValue();
        if (pressure.isEmpty()) {
            toastInfo.setValue("请输入请求压力");
            return;
        }
        try {
            int press = Integer.parseInt(pressure);
            int pressureOffset = SPHelper.getPressureOffset(getApplication());
            byte[] command2NegativePressureBoard = CommandGenerator.command2NegativePressureBoard(Const.ADDRESS_TO_NEGATIVE_PRESSURE_BOARD, -((press + pressureOffset) * 100), 0, 0, 0);
            sendMessage(command2NegativePressureBoard);
            SPHelper.saveRequestPressure(getApplication(), press);
        } catch (StructException e) {
            toastInfo.setValue("输入有误");
        }
    }

    //    底板
    public void setVBusVoltage() {
        String voltage = vBusVoltage.getValue();
        if (voltage.isEmpty()) {
            toastInfo.setValue("请求压力输入为空");
            return;
        }
        try {
            short press = Short.parseShort(voltage);
            byte[] command2BottomBoard = CommandGenerator.command2BottomBoard(Const.ADDRESS_TO_BOTTOM_BOARD, BottomBoardFunctionCode.cmd_bottombrd_Vbus_Set, (short) (press * 100));
            SPHelper.saveVBusVoltage(getApplication(), press);
            sendMessage(command2BottomBoard);
        } catch (Exception e) {
            toastInfo.setValue("请求压力输入为空输入有误");
        }
    }

    /*
     * 插入电极的升温、功率、刺入深度、针头针数、所需能量、作用时长的关系表
     * 格式需为.xls，.xlsx无法识别
     * 该功能现在不用了
     * */
    public void insertData() {
        mRepository.insertElectrodeData();
    }

    public void onSwitchBoardStateChanged(boolean isChecked) {
        try {
            byte cmd = isChecked ? (byte) 0x01 : (byte) 0x00;
            sendMessage(CommandGenerator.commandToSwitchBoard(Const.ADDRESS_TO_SWITCH_BOARD, cmd, cmd, cmd));
        } catch (StructException e) {
            throw new RuntimeException(e);
        }
    }

    public MutableLiveData<String> getToastInfo() {
        return toastInfo;
    }

    public MutableLiveData<String> getHandlePressure() {
        return handlePressure;
    }

    public MutableLiveData<String> getVBusVoltage() {
        return vBusVoltage;
    }

    public MutableLiveData<Boolean> getHasPressure() {
        return hasPressure;
    }

    public MutableLiveData<Boolean> getIsContinuousDischargeMode() {return isContinuousDischargeMode;}

//负压板数据相关
    private final MutableLiveData<List<EngineerItemBean>> pressureBoardLiveData = new MutableLiveData<>();
    public void updatePressureData(BeanFromNegativePressureBoard bean) {
        mRepository.updatePressureBoard(bean).observeForever(pressureBoardLiveData::postValue);
    }
    public LiveData<List<EngineerItemBean>> getPressureBoardLiveData() {
        return pressureBoardLiveData;
    }

//    底板数据相关
    private final MutableLiveData<List<EngineerItemBean>> bottomBoardLiveData = new MutableLiveData<>();
    public void updateBottomBoard(BeanFromBottomBoard bean) {
        mRepository.updateBottomBoard(bean).observeForever( bottomBoardLiveData::postValue);
    }
    public LiveData<List<EngineerItemBean>> getBottomBoardLiveData() {return bottomBoardLiveData;}

//    手柄数据相关
    private final MutableLiveData<List<EngineerItemBean>> handleBoardLiveData = new MutableLiveData<>();
    public void updateHandleBoard(Bean1FromHandle bean) {mRepository.updateHandleBoard(bean).observeForever(handleBoardLiveData::postValue);}
    public LiveData<List<EngineerItemBean>> getHandleBoardLiveData() {return handleBoardLiveData;}

//    切换板数据相关
    private final MutableLiveData<List<EngineerItemBean>> switchBoardData = new MutableLiveData<>();
    public void updateSwitchBoard(BeanFromSwitchBoard beanFromSwitchBoard){mRepository.updateSwitchBoard(beanFromSwitchBoard).observeForever(switchBoardData::postValue);}
    public MutableLiveData<List<EngineerItemBean>> getSwitchBoardData() {return switchBoardData;}

//    能量版数据相关
    private final MutableLiveData<List<EngineerItemBean>> energyBoardLiveData = new MutableLiveData<>();
    public void updateEnergyBoard(BeanFromEnergyBoard beanFromEnergyBoard){mRepository.updateEnergyBoard(beanFromEnergyBoard).observeForever(energyBoardLiveData::postValue);}

    public MutableLiveData<List<EngineerItemBean>> getEnergyBoardLiveData() {
        return energyBoardLiveData;
    }
}
